package com.ruoyi.system.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.DynamicOrderExcelUtil;
import com.ruoyi.system.domain.ExportSelectedRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Training;
import com.ruoyi.system.service.ITrainingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 培训管理Controller
 * 
 * @author 汪治敏
 * @date 2025-08-15
 */
@RestController
@RequestMapping("/training/training")
public class TrainingController extends BaseController
{
    @Autowired
    private ITrainingService trainingService;

    /**
     * 查询培训管理列表
     */
    @PreAuthorize("@ss.hasPermi('training:training:list')")
    @GetMapping("/list")
    public TableDataInfo list(Training training, @RequestParam(required = false, defaultValue = "true") Boolean usePage) {
        if (usePage) {
            startPage();
        }
        List<Training> list = trainingService.selectTrainingList(training);
        return getDataTable(list);
    }




    /**
     * 导入培训数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<Training> excelUtil = new ExcelUtil<>(Training.class);
        List<Training> trainingList = excelUtil.importExcel(file.getInputStream());;
        String operName = getUsername();
        String message = trainingService.importTraining(trainingList, updateSupport, operName);
        return success(message);
    }
    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<Training> excelUtil = new ExcelUtil<>(Training.class);
        excelUtil.importTemplateExcel(response, "培训数据导入模板");
    }
    /**
     * 导出培训管理列表
     */
    @PreAuthorize("@ss.hasPermi('training:training:export')")
    @Log(title = "培训管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@RequestBody Training training, HttpServletResponse response)
    {
        List<Training> list = trainingService.selectTrainingList(training);
        // 添加序号
        int startIndex = 1;
        if (training.getPageNum() != null && training.getPageSize() != null) {
            startIndex = (training.getPageNum() - 1) * training.getPageSize() + 1;
        }

        for (int i = 0; i < list.size(); i++) {
            list.get(i).setSerialNumber(startIndex + i);
        }
        ExcelUtil<Training> util = new ExcelUtil<Training>(Training.class);
        util.exportExcel(response, list, "培训管理数据");
    }
    @PostMapping("/exportSelected")
    public void exportSelected(@RequestBody List<Long> ids, HttpServletResponse response) {
        if (ids != null && !ids.isEmpty()) {
            List<Training> list = trainingService.selectTrainingListByIds(ids);

            // 添加序号
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSerialNumber(i + 1);
            }

            ExcelUtil<Training> util = new ExcelUtil<Training>(Training.class);
            util.exportExcel(response, list, "选中培训数据");
        }
    }
    /**
     * 获取培训管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:training:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(trainingService.selectTrainingById(id));
    }

    /**
     * 新增培训管理
     */
    @PreAuthorize("@ss.hasPermi('training:training:add')")
    @Log(title = "培训管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Training training)
    {
        return toAjax(trainingService.insertTraining(training));
    }

    /**
     * 修改培训管理
     */
    @PreAuthorize("@ss.hasPermi('training:training:edit')")
    @Log(title = "培训管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Training training)
    {
        return toAjax(trainingService.updateTraining(training));
    }

    /**
     * 删除培训管理
     */
    @PreAuthorize("@ss.hasPermi('training:training:remove')")
    @Log(title = "培训管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(trainingService.deleteTrainingByIds(ids));
    }
    /**
     * 生成订餐模板
     */
    @GetMapping("/generateOrderTemplate/{trainingId}")
    public void generateOrderTemplate(@PathVariable("trainingId") Long trainingId, HttpServletResponse response) throws Exception {
        // 获取培训信息
        Training training = trainingService.selectTrainingById(trainingId);
        if (training == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "培训信息不存在");
            return;
        }

        // 生成动态订餐模板
        DynamicOrderExcelUtil.generateOrderTemplate(
                response,
                training.getTrainingName(),
                training.getStartDate(),
                training.getEndDate(),
                "订餐模板"
        );
    }
    /**
     * 根据年份和月份获取培训信息
     * 该接口通过传入的年份和月份参数，获取对应的时间段的培训信息
     *
     * @param time 字符串类型，表示要查询的年份和月份，格式为"yyyy-MM"
     * @return AjaxResult 包含对应年份和月份的的培训信息的AjaxResult对象
     */
    @GetMapping("/getTrainingsByYearAndMonth")
    public AjaxResult getTrainingsByYearAndMonth(@RequestParam("time") String time) {
        if (time == null || time.isEmpty()) {
            return AjaxResult.error("时间参数不能为空");
        }

        String[] parts = time.split("-");
        if (parts.length != 2) {
            return AjaxResult.error("时间参数格式错误，应为 yyyy-MM 格式");
        }

        String year = parts[0];
        String month = parts[1];

        List<Training> trainings = trainingService.getTrainingListByYearAndMonth(year, month);
        return AjaxResult.success(trainings);
    }
}
